package com.oraclefmw.crusher.core;

import java.io.RandomAccessFile;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;

public class FileWorker extends AbstractWorker {

	private String destDir;

	public FileWorker(BlockingQueue<Fragment> queue, Properties props) {

		super(queue, props);
	}

	public synchronized void check() {

		super.check();

		destDir = props.getProperty("dest_dir");

		if (destDir == null)
			throw new IllegalArgumentException(
					"please set key 'dest_dir' for FileWorker");
	}

	@Override
	public void run() {

		check();

		for (int i = 0; i < pageSize; i++) {

			try {

				Fragment fragment = (Fragment) queue.take();

				if (fragment != null) {
					String fileName = fragment.getFileName();

					fileName = destDir + fileName;

					RandomAccessFile raFile = new RandomAccessFile(fileName,
							"rw");

					raFile.seek(fragment.getBegin());
					raFile.write(fragment.getContent());
					raFile.close();

				}
			} catch (Exception e) {

				System.err.println("writing fragment error occurs:"
						+ e.getMessage());
				e.printStackTrace();
			}
		}
	}
}
